<?php
/**
 * Created by PhpStorm.
 * User: xuzhong
 * Date: 2025/4/2
 * Time: 13:49
 */

namespace app\api\service;

use app\admin\model\Advertisement as AdvertisementModel;
use app\api\model\Images;
use app\facade\Basic;

class Advertisement
{

    protected $model;

    public function __construct()
    {
        $this->model = new AdvertisementModel();

    }

    /**
     * @describe 获取广告列表
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function getList($params): array
    {
        #验证参数
        if (!isset($params['position']) || !$params['position']) {
            return Basic::data( 100002, 'common.parameterError');
        }
        #处理查询条件
        $where = ['is_del' => 0];
        $sql = $this->model->where($where)->whereIn('position',$params['position']);
        #取数据
        $list = $sql->field('title,image,link,position,sort')->select()->toArray();
        if (!$list) {
            return Basic::data(0, 'common.success', new class {});
        }
        $photoId = array_unique(array_column($list,'image'));
        #获取图片url
        $oImages = new Images();
        $photoUrls = $oImages->getImagesByIds($photoId);
        $avatorUrls = array_column($photoUrls, null, 'id');
        #替换url
        foreach ($list as $k=>$v){
            $list[$k]['image'] = $avatorUrls[$v['image']]['url']??'';
        }
        #分组 然后排序
        usort($list, function ($a, $b) {
            if ($a['position'] === $b['position']) {
                return $a['sort'] - $b['sort'];
            }
            return $a['position'] - $b['position'];
        });
        #按position分组
        $groupedData = array_reduce(
            $list,
            function ($result, $item) {
                $positionKey = $item['position'];
                if (!isset($result[$positionKey])) {
                    $result[$positionKey] = [];
                }
                unset($item['position']);
                unset($item['sort']);
                $result[$positionKey][] = $item;
                return $result;
            },
            [] // 初始值为空数组
        );
        return Basic::data(0, 'common.success',  $groupedData);
    }



}